package com.example.usbfileutils

import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import java.io.File


class MainActivity : AppCompatActivity() {

    private val usbFileManager = USBFileManager.instance

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val btn_test: Button = findViewById(R.id.btn_test)
        btn_test.setOnClickListener {
            usbFileManager.init(this)
        }

//        val dbPath: String = getDatabasePath("cb").parent!!
//        Log.d("GJ", "dbPath: $dbPath")

        getUsbPaths()

        val btn_copy_to_usb: Button = findViewById(R.id.btn_copy_to_usb)
        btn_copy_to_usb.setOnClickListener {
            usbFileManager.copyFilesToUSB(File("$filesDir/test"), object : USBFileManager.Listener {
                override fun onStart() {
                    runOnUiThread {
                        Toast.makeText(this@MainActivity, "开始拷贝", Toast.LENGTH_SHORT).show()
                    }
                }

                override fun onComplete() {
                    runOnUiThread {
                        Toast.makeText(this@MainActivity, "拷贝完成", Toast.LENGTH_SHORT).show()
                    }
                }
            })
        }

        val btn_read_file_list: Button = findViewById(R.id.btn_read_file_list)
        btn_read_file_list.setOnClickListener {
            val fileList = usbFileManager.fetchUsbFileList("test")

            Log.d("MainActivity", "get fileList size:${fileList}")

            fileList?.forEach {
                Log.d("MainActivity", "file name: ${it.name}")
            }
        }

    }

    fun getUsbPaths(): List<String> {
        val usbPaths: MutableList<String> = ArrayList()
        val externalFilesDirs = ContextCompat.getExternalFilesDirs(this, null)
        for (file in externalFilesDirs) {
            Log.d("MainActivity", "find USB Path:" + file.absolutePath)
            if (file != null && file.exists() && !file.absolutePath.startsWith(Environment.getExternalStorageDirectory().absolutePath)) {
                usbPaths.add(file.absolutePath)
            }
        }
        return usbPaths
    }
}